from fastapi import FastAPI
from starlette.staticfiles import StaticFiles

from database import Base, engine
from routes.include_routes import include_routers
from routes.admin_routes import RouteManager
from middleware.jwt_middleware import JwtMiddleware
from fastapi.middleware.cors import CORSMiddleware
import asyncio

# 创建 FastAPI 应用实例
app = FastAPI()
# app.mount("/images", StaticFiles(directory="images/detect"), name="images")
app.mount("/images/user/avatar", StaticFiles(directory="images/user_avatar"), name="avatar")
app.mount("/upload/images/", StaticFiles(directory="upload/images/"), name="images")
app.add_middleware(JwtMiddleware)
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许所有来源
    allow_credentials=True,
    allow_methods=["*"],  # 允许所有方法
    allow_headers=["*"],  # 允许所有头
)


# 应用启动事件
@app.on_event("startup")
async def startup_event():
    # 在应用启动时创建数据库表（如果不存在）
    Base.metadata.create_all(bind=engine)

    # Start your TCP Server


# 路由注册
include_routers(app)
# 创建路由管理器实例并获取路由
route_manager = RouteManager()
app.include_router(route_manager.get_router())
# 应用关闭事件
# @app.on_event("shutdown")
# async def shutdown_event():
#     # 在应用关闭时可以进行一些清理操作或资源释放

# 运行 FastAPI 应用
if __name__ == "__main__":
    import uvicorn

    uvicorn.run("main:app", host="0.0.0.0", port=9030, reload=True)
